package panda.query.condition;

import java.util.ArrayList;
import java.util.List;

import panda.query.scan.Scanner;
import panda.query.struct.Attribute;
import panda.query.tree.QueryTreeNode;
import panda.transaction.Transaction;

/**
 * The propositional expression corresponding to <i>AND</i> in SQL
 * Assume the expression is a CNF
 * @author Tian Yuan 
 * 
 */
public class Sentence implements BooleanExpression{
	
	List<Clause> clauses = new ArrayList<Clause>();
	
	/**
	 * 
	 */
	public Sentence() {
		
	}
	
	/**
	 * 
	 * @param b
	 */
	public Sentence(Clause b) {
		clauses.add(b);
	}
	
	/**
	 * 
	 * @param b
	 */
	public void addClause(Clause b) {
		clauses.add(b);
	}
	
	/**
	 * 
	 * @param s
	 * @return
	 */
	public int isSatisfied(Scanner s, Transaction tx) {
		boolean un = false; 
		for (int i = 0; i < clauses.size(); i++) {
			int res = clauses.get(i).isSatisfied(s, tx);
			
			if (res == -1) return -1;
			if (res == 0) un = true;
		}
			
		if (un) return 0; else return 1;
	}

	public int equateWithConstant(Attribute attr) {
		for (int i = 0; i < clauses.size(); i++) {
			int c = clauses.get(i).equateWithConstant(attr);
			if (c != 0)
				return c;
		}
		return 0;
	}

	public double reductionFactor(QueryTreeNode n) {
		double factor = 1;
		for (int i = 0; i < clauses.size(); i++)
			factor *= clauses.get(i).reductionFactor(n);
		return factor;
	}

}
